﻿using System;
using MySql.Data.MySqlClient;

namespace DevOnServer
{
    public class CDatabaseConnection : IDisposable
    {
        public bool connect(string host, int port, string username, string password, string database)
        {
            if (m_mysql == null)
                m_mysql = new MySqlConnection();

            m_mysql.ConnectionString = "server=" + host + ";user=" + username + ";database=" + database + ";port=" + port + ";password=" + password + ";";

            try
            {
                m_mysql.Open();
            }
            catch (Exception e)
            {
                CConsole.WriteLine("MySql connection error: {0}", e.Message);
                m_mysql = null;
                return false;
            }

            return true;
        }

        public bool query(string format, params object[] args)
        {
            m_queriesCount++;
            string query = String.Format(format, args);

            try
            {
                MySqlCommand cmd = new MySqlCommand(query, m_mysql);
                cmd.ExecuteNonQuery();
                cmd = null;
            }
            catch (Exception e)
            {
                CConsole.WriteLine("MySql execute non query error: {0}", e.Message);
                return false;
            }

            return true;
        }

        public CQueryResult result(string format, params object[] args)
        {
            string query = String.Format(format, args);
            MySqlDataReader rdr = null;

            try
            {
                MySqlCommand cmd = new MySqlCommand(query, m_mysql);
                rdr = cmd.ExecuteReader();
                return new CQueryResult(rdr);
            }
            catch (Exception e)
            {
                if (rdr != null)
                    rdr.Close();

                CConsole.WriteLine("MySql execute reader error: {0}", e.Message);
                return null;
            }
        }

        public int QueryCount
        {
            get
            {
                return m_queriesCount;
            }
        }

        public bool ping()
        {
            return m_mysql.Ping();
        }

        public void Dispose()
        {
            if (m_mysql != null)
            {
                m_mysql.Close();
                m_mysql = null;
            }
        }

        public string escapeString(string str)
        {
            str = str.Replace("\"", "\\\"");
            str = str.Replace("\\", "\\\\");
            return str;
        }

        private MySqlConnection m_mysql;

        private int m_queriesCount;
    }
}